const models = require('../models')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const secretKey = '23123123@##@$'

// 用户登录
exports.getUserList = async (req, res, next) => {
    try {        
        const newPwd = bcrypt.hashSync('123456', 10)
        console.log(newPwd)

        // 验证比对,返回布尔值表示验证结果 true表示一致，false表示不一致
        const isOk = bcrypt.compareSync('123456', newPwd)
        console.log('比较密码的结果', isOk)

        let list = await models.User.findAll()
        res.status(200).send(list)
    } catch (error) {
        next(error)
    }
}

// 用户登录
exports.login = async (req, res, next) => {
    try {
        const user = req.body
        let find = await models.User.findOne({
            where: {
                firstName: user.firstName,
                lastName: user.lastName
            }
        })
        if (!find) {
            return res.status(422).json({message: '用户名或密码错误，登录失败'})
        }
        const token = jwt.sign({ id: find.id }, secretKey)
        res.status(200).send({message: '登录成功', data: user, token})
    } catch (error) {
        next(error)
    }
}

// 用户注册
exports.register = async (req, res, next) => {
    try {
        const user = req.body
        let find = await models.User.findOne({
            where: {
                firstName: user.firstName,
                lastName: user.lastName
            }
        })
        if (find) {
            return res.send({ message: '你注册的用户已经存在' })
        }
        let createUser = await models.User.create(user)
        console.log(createUser)
        res.status(201).json({
            message:'注册成功',
            data: createUser
        })
    } catch (error) {
        next(error)
    }
}

// 获取当前登录用户
exports.getCurrentUser = async (req, res, next) => {
    try {
        /*
        console.log(req.headers.authorization)
        const token = req.headers.authorization.split(' ')[1]
        const tokenData = jwt.verify(token, secretKey)
        console.log(tokenData)
        const user = await models.User.findOne({
            where: {
                id: tokenData.id
            }
        })
        if (!user) {
            return res.status(422).json({
                message: '您的token失效或不正确'
            })
        }
        res.send(user)
        */
        console.log(req.user)
        const user = await models.User.findOne({
            where: {
                id: req.user.id
            }
        })
        res.send(user)
    } catch (error) {
        next(error)
    }
}

// 更新当前登录用户
exports.updateCurrentUser = async (req, res, next) => {
    try {
        // 处理请求
        res.send('updateCurrentUser')
    } catch (error) {
        next(error)
    }
}